<?php

namespace App\Http\Controllers\Develop;

use DB;

use Carbon\Carbon;

use Illuminate\Http\Request;

use App\Models\User\Permission;

use App\Models\User\PermissionGroup;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

class PermissionGroupController extends Controller
{

    /**
     * 打开权限组页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {

        $level = $request->input('level', 2);
        $data['level'] = $level;

        //查询一级权限组信息
        $group = PermissionGroup::where('parent_id', 0)->get();
        $data['group'] = $group;

        return view('develop/permissionGroupList', $data);

    }

    /**
     * 权限组分页查询
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function search(Request $request)
    {

        $where = [];
        $level = $request->input('level', 2);
        $parent_id = $request->input('parent_id', 0);
        $group_name = $request->input('group_name');

        //查询条件
        if ($level == 1) {
            $where[] = ['parent_id', 0];
        } else {
            if ($parent_id > 0) {
                $where[] = ['parent_id', $parent_id];
            } else {
                $where[] = ['parent_id', '>', 0];
            }
        }
        if (!empty($group_name)) {
            $where[] = ['group_name', 'like', '%' . $group_name . '%'];
        }

        $groups = PermissionGroup::where($where)
            ->orderBy($request->input('sort'), $request->input('order'))
            ->paginate($request->input('limit'))
            ->toArray();

        //返回数组
        $return = [
            'total' => $groups['total'],
            'rows' => []
        ];

        foreach ( $groups['data'] as &$row ) {

            $operation = '<a href="javascript: void(0);" onclick="PermissionGroup.edit(' . $row['group_id'] . ');">修改</a>&nbsp&nbsp';
            $operation .= '<a href="javascript: void(0);" onclick="PermissionGroup.del(' . $row['group_id'] . ');">删除</a>';

            if ($level == 1) {
                $parent_group_name = '';
            } else {
                $parent_group = PermissionGroup::find($row['parent_id']);
                if (!$parent_group) {
                    continue;
                }
                $parent_group_name = $parent_group->group_name;
            }

            $return['rows'][] = [
                'operation' => $operation,
                'group_name' => $row['group_name'],
                'permission_num' => $row['permission_num'],
                'sort' => $row['sort'],
                'min_permission_id' => $row['min_permission_id'],
                'max_permission_id' => $row['max_permission_id'],
                'parent_group_name' => $parent_group_name
            ];
            
        }

        return response()->json($return);

    }

    /**
     * 单条权限组信息
     * @param int $id 权限组id
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function get($id)
    {

        $group = PermissionGroup::select('group_id','group_name','min_permission_id','max_permission_id','parent_id','sort')->find($id);
        if ($group) {
            return response()->json(['code' => 200, 'message' => 'OK', 'data' => $group]);
        } else {
            return response()->json(['code' => 100001, 'message' => '权限组不存在']);
        }

    }

    /**
     * 删除权限组
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function store(Request $request)
    {

        $sort = $request->input('sort');
        $level = $request->input('level');
        $group_id = $request->input('group_id');
        $parent_id = $request->input('parent_id');
        $group_name = $request->input('group_name');
        $min_permission_id = $request->input('min_permission_id');
        $max_permission_id = $request->input('max_permission_id');

        if (!in_array($level, [1, 2])) {
            return response()->json(['code' => 100001, 'message' => '参数错误']);
        }

        if (!ebsig_is_int($group_id)) {
            $group_id = 0;
        }

        if ($level == 1) {
            $parent_id = 0;
        } else {
            if (!ebsig_is_int($parent_id)) {
                return response()->json(['code' => 100002, 'message' => '一级权限组不能为空']);
            }
        }

        if (empty($group_name)) {
            return response()->json(['code' => 100003, 'message' => '权限组名称不能为空']);
        }

        if (!ebsig_is_int($min_permission_id)) {
            return response()->json(['code' => 100004, 'message' => '最小权限ID不能为空']);
        }

        if (!ebsig_is_int($max_permission_id)) {
            return response()->json(['code' => 100005, 'message' => '最大权限ID不能为空']);
        }

        if (!ebsig_is_int($sort)) {
            return response()->json(['code' => 100005, 'message' => '排序序号不能为空']);
        }

        //检查一级权限组是否存在
        if ($parent_id > 0) {
            $parent_group = PermissionGroup::find($parent_id);
            if (!$parent_group || $parent_group->parent_id > 0) {
                return response()->json(['code' => 100005, 'message' => '一级权限组不存在']);
            }
        }

        if ($group_id > 0) {
            $group = PermissionGroup::find($group_id);
            if (!$group) {
                return response()->json(['code' => 100006, 'message' => '权限组不存在']);
            }
        } else {
            $group = new PermissionGroup();
            $group->uuid = makeUuid();
            $group->timeStamp = Carbon::now();
            $group->creator = Redis::get('WDH_ADMIN_USER_ID_' . session_id());
            $group->createTime = Carbon::now();
            $group->permission_num = 0;
        }
        $group->group_name = $group_name;
        $group->min_permission_id = $min_permission_id;
        $group->max_permission_id = $max_permission_id;
        $group->parent_id = $parent_id;
        $group->sort = $sort;
        $group->save();

        return response()->json(['code' => 200, 'message' => 'OK']);

    }

    public function delete($id)
    {

        DB::beginTransaction();

        try {

            //查询权限组
            $group = PermissionGroup::find($id);
            if (!$group) {
                return response()->json(['code' => 100001, 'message' => '权限组不存在']);
            }

            if ($group->parent_id == 0) { //一级权限组

                //删除二级权限
                PermissionGroup::where('parent_id', $id)->delete();

                //删除权限
                Permission::where('permissionGroupID', $id)->delete();

            } else { //二级权限组

                //删除权限
                Permission::where('secondLevelPermissionGroupID', $id)->delete();
                
            }
            $group->delete();

            DB::commit();

        } catch (\Exception $e) {

            DB::rollback();

        }

        return response()->json(['code' => 200, 'message' => 'OK']);

    }


}
